package com.weather.ui;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.weather.R;
import com.weather.bean.AccurealFeelResult;
import com.weather.bean.IndexIcon;
import com.weather.bean.MinuteNew;
import com.weather.bean.YinpinResult;
import com.weather.ui.mvp.Constant;
import com.weather.ui.mvp.PresenterImp;
import com.weather.utils.FileUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements Constant.View,
        MediaPlayer.OnCompletionListener {
    private static String TAG = "====MainActivity====";
    @BindView(R.id.play_fab)
    FloatingActionButton playFab;
    private String MP3Path;
    private boolean isPlay = false;
    private boolean isReady = false;
    Constant.Presenter presenter;
    @BindView(R.id.tianqi_iv)
    ImageView tianqiIv;
    @BindView(R.id.realfeel_tv)
    TextView realfeelTv;
    @BindView(R.id.minuteNew_tv)
    TextView minuteNewTv;
    @BindView(R.id.appIndexAll_tv)
    TextView appIndexAllTv;
    @BindView(R.id.accurealFeel_tv)
    TextView accurealFeelTv;
    @BindView(R.id.keyword_tv)
    TextView keywordTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        presenter = new PresenterImp(this);
        Map<String, String> map = getLoaction();
        if (map != null) {
            presenter.getMinuteNew(map);
        }
        presenter.getAppIndexAll();
        presenter.getAccurealFeel();
        presenter.getYinpin();
        presenter.getKeywordNew();
    }

    @Override
    public void showMinuteNew(Object result) {
        MinuteNew minuteNew = (MinuteNew) result;
        minuteNewTv.setText(minuteNew.getMsg());
        Context context = this;
        switch (minuteNew.getAmendNowwcode()) {
            case "00":
                Glide.with(context).load(R.drawable.day00_mini).override(50, 50).into(tianqiIv);
                break;
            case "01":
                Glide.with(context).load(R.drawable.day01_mini).override(50, 50).into(tianqiIv);
                break;
            case "02":
                Glide.with(context).load(R.drawable.day02_mini).override(50, 50).into(tianqiIv);
                break;
            case "03":
                Glide.with(context).load(R.drawable.day03_mini).override(50, 50).into(tianqiIv);
                break;
            case "04":
                Glide.with(context).load(R.drawable.day04_mini).override(50, 50).into(tianqiIv);
                break;
            case "05":
                Glide.with(context).load(R.drawable.day05_mini).override(50, 50).into(tianqiIv);
                break;
            case "06":
                Glide.with(context).load(R.drawable.day06_mini).override(50, 50).into(tianqiIv);
                break;
            case "07":
                Glide.with(context).load(R.drawable.day07_mini).override(50, 50).into(tianqiIv);
                break;
            case "11":
                Glide.with(context).load(R.drawable.day11_mini).override(50, 50).into(tianqiIv);
                break;
            case "13":
                Glide.with(context).load(R.drawable.day13_mini).override(50, 50).into(tianqiIv);
                break;
            case "14":
                Glide.with(context).load(R.drawable.day14_mini).override(50, 50).into(tianqiIv);
                break;
            case "15":
                Glide.with(context).load(R.drawable.day15_mini).override(50, 50).into(tianqiIv);
                break;
            case "16":
                Glide.with(context).load(R.drawable.day16_mini).override(50, 50).into(tianqiIv);
                break;
            case "17":
                Glide.with(context).load(R.drawable.day17_mini).override(50, 50).into(tianqiIv);
                break;
            case "18":
                Glide.with(context).load(R.drawable.day18_mini).override(50, 50).into(tianqiIv);
                break;
            case "19":
                Glide.with(context).load(R.drawable.day19_mini).override(50, 50).into(tianqiIv);
                break;
            case "31":
                Glide.with(context).load(R.drawable.day31_mini).override(50, 50).into(tianqiIv);
                break;
            case "32":
                Glide.with(context).load(R.drawable.day32_mini).override(50, 50).into(tianqiIv);
                break;
            case "33":
                Glide.with(context).load(R.drawable.day33_mini).override(50, 50).into(tianqiIv);
                break;
            case "35":
                Glide.with(context).load(R.drawable.day35_mini).override(50, 50).into(tianqiIv);
                break;
            case "53":
                Glide.with(context).load(R.drawable.day53_mini).override(50, 50).into(tianqiIv);
                break;
            default:
                break;
        }
    }

    @Override
    public void showAppIndexAll(Object result) {
        final IndexIcon indexIcon = (IndexIcon) result;
        appIndexAllTv.setText(indexIcon.getDes());
        final Context context = this;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final Bitmap bitmap = Glide.with(context)
                            .load(indexIcon.getImage())
                            .asBitmap()
                            .into(80, 80).get();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Drawable drawable = new BitmapDrawable(bitmap);
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                                    drawable.getIntrinsicHeight());
                            appIndexAllTv.setCompoundDrawables(drawable, null, null, null);
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void showAccurealFeel(Object result) {
        AccurealFeelResult feel = (AccurealFeelResult) result;
        accurealFeelTv.setText(feel.getText());
        String realfeel = "体感温度:\n" + feel.getRealfeel();
        int start = realfeel.indexOf(":") + 1;
        SpannableString span = new SpannableString(realfeel);
        span.setSpan(new RelativeSizeSpan(2), start, realfeel.length(),
                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        realfeelTv.setText(span);
    }

    @Override
    public void showYinpin(Object result) {
        YinpinResult yinpinResult = (YinpinResult) result;
        Log.e(TAG, yinpinResult.getAudio());
        String[] split = yinpinResult.getAudio().split("/");
        String s = split[split.length - 1];
        File file = new File(FileUtils.getAudioCacheFile(), s);
        this.MP3Path = file.getAbsolutePath();
        if (!file.exists()) {
            presenter.downYinpin(s);
        } else {
            Log.e(TAG, "应该变白");
            isReady = true;
            playFab.setBackgroundColor(Color.WHITE);
        }
    }

    @Override
    public void showKeywordNew(Object result) {
        keywordTv.setText((CharSequence) result);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.e(TAG, "播放结束监听运行了");
        isPlay = false;
    }
    @Override
    public void setIsReady(boolean result) {
        this.isReady = result;
        if (isReady) {
            Log.e(TAG, "setIsReady");
            playFab.setBackgroundColor(Color.WHITE);
        }
    }

    @OnClick(R.id.play_fab)
    public void onClick() {
        Log.e(TAG, "onClick");
        if (!isPlay) {
            Intent intent = new Intent(this, PlayService.class);
            intent.putExtra("play", isPlay);
            intent.putExtra("path", this.MP3Path);
            startService(intent);
            isPlay = true;
        } else {
            if (isReady) {
                Toast.makeText(this, "正在播放，请稍候", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "正在下载，请稍候", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private Map<String, String> getLoaction() {
        LocationManager manager = (LocationManager) this.
                getSystemService(Context.LOCATION_SERVICE);
        //设置服务商的信息
        Criteria criteria = new Criteria();
        //提供服务的精度标准
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //不需要高度信息
        criteria.setAltitudeRequired(false);
        //不需要方位信息
        criteria.setBearingRequired(false);
        //不允许产生费用
        criteria.setCostAllowed(false);
        //消耗电力为低
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        //取得最匹配的criteria
        String provider = manager.getBestProvider(criteria, true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.
                checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            return null;
        }
        Location location = manager.getLastKnownLocation(provider);
        String latstr = String.valueOf(location.getLatitude());
        String lonstr = String.valueOf(location.getLongitude());
        Map<String,String> map = new HashMap<>();
        map.put("latstr",latstr);
        map.put("lonstr",lonstr);
        return map;
    }
}
